#encoding=utf-8  
import telnetlib 
import time
import re
import socket
import struct

bsi_interval = 0.5;

epc_udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM); #udp
pack_pattern = struct.Struct('BBH')    #u8 ,(8bits padding), u16
#"      30        -36.3130    -100.0000    -36.3130     -82.8130          0               4           11      0       1       0       4"               
#\s*(\d+)\s+(-*\d+\.*\d+)\s+(-*\d+\.*\d+)\s+(-*\d+\.*\d+)\s+(-*\d+\.*\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)                      bsi_list = []
reobj = re.compile('\s*(\d+)\s+(-*\d+\.*\d+)\s+(-*\d+\.*\d+)\s+(-*\d+\.*\d+)\s+(-*\d+\.*\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)')
logHandler = open("bsi_based_on_udp.log", "w")
udp_sequence = 0

def send_to_epc(beamid):
    global udp_sequence
    values = (beamid,0,udp_sequence)

    global pack_pattern                             
    packed_data = pack_pattern.pack(*values)   #pack it

    global epc_udp;

    epc_add  = "192.168.10.254";
    #epc_add  = "10.140.163.115";
    epc_udp_port = 44230;
    epc_udp.sendto(packed_data,(epc_add, epc_udp_port))
    udp_sequence += 1
    if (udp_sequence > 65535):
        udp_sequence = 0;
    

def brs_analyse(echo_back):
       
    echo_back_lines =  echo_back.split("\n")

    brs_string = "BRS best 8 measurements seen so far"
    #print lllll
    Pos = 0;
    for i in echo_back_lines:
        if  brs_string in i:
            break;
        Pos += 1;

    BRSinfo = [];
    if Pos < len(echo_back_lines) and Pos+10 < len(echo_back_lines):
        BRSinfo =  echo_back_lines[Pos:Pos+10]

    beam_counter = [0]*28;
    global reobj;
    bsi_list = []
    for i in  BRSinfo:   
        res = reobj.search(i)
        if res:
            Symbol = int(res.group(8))
            BrsSf = int(res.group(10))
            bsi = Symbol + BrsSf * 14
            if bsi >=0 and bsi < 28:
                beam_counter[bsi] += 1; 
        else:
            #print "no match", i;
            pass

    maxRef_index = 0;
    for i in range(28):
        if beam_counter[i] > beam_counter[maxRef_index]:
            maxRef_index = i;

    print maxRef_index, beam_counter[maxRef_index]
    logHandler.write("brsinfo:\r\n "+echo_back+"\r\n")
    if maxRef_index == 0:
        if beam_counter[maxRef_index] > 6 :
	        return maxRef_index
    elif beam_counter[maxRef_index] > 3:
        return maxRef_index
    else:
        logHandler.write("No valid bsi in brsinfo:\r\n "+echo_back+"\r\n")
        #for i in  BRSinfo:
        #    print "brs_analyse:"
        #    print i;
        return -1

def run():   

    Host = "192.168.0.20"           # Telnet server IP  
    Port = 23                         # Telnet server port

    cmdline_prompt = "->"
    tn = telnetlib.Telnet(Host, Port, timeout=5)  
    tn.set_debuglevel(0)  

    tn.read_until("#") 
    cmd = "C"	
    tn.write(cmd + '\n') 

    time.sleep(3)

    print tn.read_until(cmdline_prompt)

    while True:
        cmd = "mtally"
        tn.write(cmd + '\n')   
        echo_back = tn.read_until(cmdline_prompt)   

        bsi = brs_analyse(echo_back)

        if bsi >= 0 and bsi < 28: 
            send_to_epc(bsi)
            global udp_sequence
            sentinfo = "[%s] Bsi %u(seq:%u) was sent to epc"%(time.strftime("%H:%M:%S"), bsi, udp_sequence)
            print sentinfo
            logHandler.write(sentinfo)

        global bsi_interval;    
        time.sleep(bsi_interval)

if __name__ == '__main__':
    run()

epc_udp.close()
logHandler.close()